<template>
  <div class="mod-config">
    <split-pane class="splitPane" :min-percent='10' :default-percent='10' split="vertical">
      <template slot="paneL">
        <div class="treeViewContainer">
          <tree-view ref="treeView" :treeData="statusTreeList" :checkChangedHandler="getDataList"></tree-view>
        </div>
      </template>
      <template slot="paneR">
        <table-view ref="view"
                    :searchAttrs="searchAttrs"
                    :primaryKey="primaryKey"
                    :listApiName="listApiName"
                    :deleteApiName="deleteApiName"
                    :saveAuthName="saveAuthName"
                    :deleteAuthName="deleteAuthName"
                    :showAttrs="showAttrs"
                    :searchFormShowNumber="3"
                    :optionWidth="200"
        >
          <template  v-slot:header>
            <el-button v-if="isAuth(orderDetailExportAuthName)" size="small" type="danger"  >导出产品库存</el-button>
          </template>
          <template v-slot:foot="{scope}">
            <el-tooltip class="item" effect="dark" content="查询库存" placement="bottom" :hide-after="1800" :open-delay="800">
              <el-button size="small" type="text" @click="showInventory(R.path(['row', primaryKey], scope))">
                查询库存
              </el-button>
            </el-tooltip>
          </template>
        </table-view>
      </template>
    </split-pane>


    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <modelinfo-add-or-update v-if="modelInfoVisible" ref="modelInfo"></modelinfo-add-or-update>

    <el-dialog title="库存" :visible.sync="inventoryDialog" :fullscreen="true" v-loading="inventoryLoading" >
      <el-table :data="inventoryDataList" border style="width: 100%;" show-summary :summary-method="getSummaries" >
        <el-table-column prop="orderDetailNo" header-align="center" align="center" label="订单编号"></el-table-column>
        <el-table-column prop="clientName" header-align="center" align="center" label="客户名称"></el-table-column>
        <el-table-column prop="orderProductNumber" header-align="center" align="center" label="订单数量"></el-table-column>
        <el-table-column prop="productWeight" header-align="center" align="center" label="克数"></el-table-column>
        <el-table-column prop="putInStorageValue" header-align="center" align="center" label="入库数量"></el-table-column>
        <el-table-column prop="allocationToValue" header-align="center" align="center" label="调拨入库数量"></el-table-column>
        <el-table-column prop="leaveStorageValue" header-align="center" align="center" label="出库数量"></el-table-column>
        <el-table-column prop="allocationFromValue" header-align="center" align="center" label="调拨出库数量"></el-table-column>
        <el-table-column prop="lossLightBottleValue" header-align="center" align="center" label="损耗数量"></el-table-column>
        <el-table-column prop="inventory" header-align="center" align="center" label="剩余数量"></el-table-column>
      </el-table>
      <el-pagination
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="pageIndex"
        :page-sizes="[50,100,200]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <span slot="footer" class="dialog-footer">
        <el-button @click="inventoryDialog = false">取 消</el-button>
        <el-button type="primary" @click="inventoryDialog = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AddOrUpdate from './productinfo-add-or-update'
import tableView from '@/components/tableView'
import basicMixins from '@/utils/commonViewMixins'
import {mRequest} from '@/utils/request'
import ModelinfoAddOrUpdate from '@/views/modules/model/modelinfo-add-or-update'
import {isAuth} from '@/utils'
import treeView from '@/components/treeView.vue'

export default {
  mixins: [basicMixins],
  data() {
    return {
      isAuth: isAuth,
      statusTreeList: [],
      inventoryDataList: [],
      inventoryLoading: false,
      inventoryDialog: false,
      modelInfoVisible: false,
      pageIndex: 1,
      pageSize: 100,
      totalPage: 0,
      searchAttrs: {
        productNo: {
          label: '产品编号',
          placeholder: '请输入产品编号'
        },
        productWeight: {
          label: '产品重量',
          placeholder: '请输入产品重量'
        },
        lengthWeightHeight: {
          label: '产品规格',
          placeholder: '请输入规格'
        },
        productVolume: {
          label: '产品容量',
          placeholder: '请输入产品容量'
        },
        bottleOutDiameter: {
          label: '瓶口外径',
          placeholder: '请输入瓶口外径'
        },
        productCategoryId: {
          type: 'func',
          dataFunc: () => {
            return this.$refs.treeView.$refs.treeForm.getCheckedKeys()[0]
          }
        }
      },
      primaryKey: 'id',
      listApiName: 'productApi/listProductInfo',
      deleteApiName: 'productApi/deleteProductInfo',
      saveAuthName: 'product:productinfo:save',
      deleteAuthName: 'product:productinfo:delete',
      templateDownloadApiName: 'productApi/templateDownloadProductInfo',
      importApiName: 'productApi/importProductInfo',
      orderDetailExportAuthName: 'order:orderdetail:orderDetailExport',
      showAttrs: {
        productNo: {label: '产品型号', width: 160},
        countNumber: {label: '结余数量'},
        purchaseUntPrice: {label: '采购单价', width: 140},
        productImageId: {label: '图片', type: 'image'},
        bottleOutDiameter: { label: '口径' },
        productVolume: {label: '容量(ml)'},
        productWeight: {label: '克数'},
        relateColor: {label: '颜色'},
        relateMaterial: {label: '材质'},
        relateSize: {label: '尺寸'},
        boxPackingQuantity: { label: '装箱数量' },
        changeImageStatus: { label: '图片更新',
          type: 'radio',
          items: [
            {value: 0, text: '未更新',tagType: 'info'},
            {value: '', text: '未更新',tagType: 'info'},
            {value: 1, text: '更新',tagType:'success'}
          ] },
        headNeckHeight: {label: '头高'},
        grossWeight: { label: '毛重（kg）', width: 100 },
        boxCartonSize: { label: '箱规(cm)' , width: 140},
        productDrawingId: {label: '图纸', showKey: 'productNo', type: 'file', width: 140},
        productCategoryName: {label: '分类'},
        remark: {label: '备注'},
        // successRate: {label: '成品率'}
      }
    }
  },
  methods: {
    statusTreeListInit() {
      mRequest('productApi/getProductCategoryListByUser', {}, (res) => {
        const statusTreeList = this.R.pathOr([], ['data', 'list'], res)
        const productCategoryTreeList = [{
          id: '',
          name: '产品类别列表',
          nodeType: 0,
          children: []
        }]
        productCategoryTreeList[0].children = statusTreeList
        this.statusTreeList = productCategoryTreeList;
      })
    },
    showInventory(id) {
      this.inventoryDialog = true
      this.inventoryLoading = true
      this.productId=id
      this.getDataListBySelectProduct()
    },

    getDataListBySelectProduct() {
      let params = {
        productId: this.productId,
        page: this.pageIndex,
        limit: this.pageSize
      }

      mRequest('orderApi/getOrderDetailPageByProductId', params, (res) => {
        const list = this.R.pathOr([], ['data', 'page','list'], res)
        const totalCount = this.R.pathOr([], ['data','page', 'totalCount'], res)
        this.totalPage = totalCount
        this.inventoryDataList = this.R.map((item) => ({
          orderDetailId: this.R.propOr('', 'id', item),
          orderDetailNo: this.R.propOr('', 'orderNo', item),
          orderProductNumber: this.R.propOr('0', 'orderProductNumber', item),
          productWeight: this.R.propOr(0, 'productWeight', item),
          clientName: this.R.propOr('', 'clientName', item),
          putInStorageValue: this.R.propOr(0, 'putInStorageValue', item),
          leaveStorageValue: this.R.propOr(0, 'leaveStorageValue', item),
          allocationFromValue: this.R.propOr(0, 'allocationFromValue', item),
          allocationToValue: this.R.propOr(0, 'allocationToValue', item),
          lossLightBottleValue: this.R.propOr(0, 'lossLightBottleValue', item),
          inventory: this.R.propOr(0, 'putInStorageValue', item)+
            this.R.propOr(0, 'allocationToValue', item) -
            this.R.propOr(0, 'leaveStorageValue', item)-
            this.R.propOr(0, 'allocationFromValue', item)-
            this.R.propOr(0, 'lossLightBottleValue', item)
        }), list)
      })
      this.inventoryLoading = false
    },
    openModelInfoDialog(cb) {
      this.modelInfoVisible = true
      this.$nextTick(() => {
        if (!this.R.isNil(this.$refs.modelInfo)) {
          this.$refs.modelInfo.init(null, {status: 1}, cb)
        }
      })
    },
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataListBySelectProduct()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataListBySelectProduct()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val

    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1) {
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        }
      });

      return sums;
    }
  },
  mounted() {
    this.statusTreeListInit()
  },
  components: {
    tableView,
    treeView,
    ModelinfoAddOrUpdate,
    AddOrUpdate
  }
}
</script>
